<?php

namespace Keio\StudyBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Keio\StudyBundle\Entity\User;
use Keio\StudyBundle\Form\UserType;
use Symfony\Component\Form\FormError;
use Keio\StudyBundle\Entity\Packageuser;

/**
 * User controller.
 *
 */
class UserController extends Controller
{

    /**
     * Lists all User entities.
     *
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('KeioStudyBundle:User')->findAll();

        //set delete form cho mỗi element
        foreach ($entities as $entity){
        	$deleteForm = $this->createDeleteForm($entity->getId());
        	$entity->setDelform($deleteForm->createView());
        }

        return $this->render('KeioStudyBundle:User:index.html.twig', array(
            'entities' => $entities,
        ));
    }
    public function listmemberAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('KeioStudyBundle:User')->findAll();

        //set delete form cho mỗi element
        foreach ($entities as $entity){
        	$deleteForm = $this->createDeleteForm($entity->getId());
        	$entity->setDelform($deleteForm->createView());
        }

        return $this->render('KeioStudyBundle:User:list_member.html.twig', array(
            'entities' => $entities,
        ));
    }
    //show va add package to member
	public function showpackagememberAction($member_id){
		//lấy các package đã gắn vào package
		$em = $this->getDoctrine()->getManager();
		$member = $em->getRepository('KeioStudyBundle:User')->find($member_id);

		if (in_array('ROLE_USER', $member->getRoles())){
			$member_is_user = 1;
		}else{
			$member_is_user = 0;
		}

		$packageY = $em->getRepository('KeioStudyBundle:Package')->getPackageByUser($member_id);
		$packageYid = $packageY['pkgsid'];
		$packageN = $em->getRepository('KeioStudyBundle:Package')->getPackageExcludeSomeId($packageYid);
		//đẩy lên view
		return $this->render('KeioStudyBundle:User:add_package_member.html.twig', array(
            'packageY' => $packageY['pkgs'],
			'packageN' => $packageN,
            'memberid'   => $member->getId(),
            'member_is_user' => $member_is_user,
        ));
	}
    //add package vào member. Chỉ xử lý nếu user có profile là member thôi.
    public function addpackagetomemberAction($member_id)
    {
        $request = $this->getRequest();
		$array_package = $request->request->get('package');

		$em = $this->getDoctrine()->getManager();
		$user = $em->getRepository('KeioStudyBundle:User')->find($member_id);

		for ($j=0; $j<count($array_package); $j++){
			//nếu package chưa đc submit từ form thì count này bằng 0 nên ko chạy ở đây
			$pkg = $em->getRepository('KeioStudyBundle:Package')->find($array_package[$j]);
			$tmp = new Packageuser();
			$tmp->setUser($user);
			$tmp->setPackage($pkg);
			$em->persist($tmp);
        	$em->flush();
		}
		return $this->redirect($this->generateUrl('admin_user_showpackagemember', array('member_id'=>$member_id)));
    }
    /**
     * Creates a new User entity.
     *
     */
    public function createAction(Request $request)
    {
		$request = $this->getRequest();
		//check if from admin user creation or from register
		$admcheck = $request->request->get('admcheck');

		$data_form = $request->request->get('keio_studybundle_usertype');
    	$username = trim($data_form['username']);
    	$password = $data_form['password'];
    	$repeatpwd  = $data_form['passwordR'];

    	if ($admcheck==1){ //tạo user từ administration
	    	$roles = $request->request->get('roles');
    	}else{
    		$roles = array('ROLE_USER');
    	}

		$em = $this->getDoctrine()->getManager();
		$user = new User();
        $user->setUsername($username);

        $user->setRoles($roles);
        $user->setHoten($data_form['hoten']);
        $user->setEmail($data_form['email']);
        $user->setDienthoai($data_form['dienthoai']);
        $user->setDotuoi($data_form['dotuoi']);

        $form = $this->createForm(new UserType(), $user);

        //chech nếu form có lỗi
        $check_form = $em->getRepository('KeioStudyBundle:User')->checkFieldErrorsOfUser(0, $username, $data_form['email'], $password, $repeatpwd, $roles);
        if ($check_form['ok']==0){//có lỗi
        	$form->addError(new FormError($check_form['msg']));
        }
        else{
        	// encode the password (nếu có điền password)
        	if(strlen($password)!=0){
        		$factory = $this->get('security.encoder_factory');
		        $encoder = $factory->getEncoder($user);
		        $encodedPassword = $encoder->encodePassword($password, $user->getSalt());
		        $user->setPassword($encodedPassword);
        	}
	        $em->persist($user);
	        $em->flush();
	        if ($admcheck==1){ //tạo user từ administration
	        	return $this->redirect($this->generateUrl('admin_user'));
	        }else{ //tạo user bằng registration
	        	return $this->render('KeioStudyBundle:Member:register_success.html.twig', array(
	            	'username'   => $username,
	        	));
	        }
        }
        //if failed
        if ($admcheck==1){ //tạo user từ administration
	        $roleschecked = array(1=>0, 2=>0, 3=>0);
	        if (count($roles)!=0){
	        	if (in_array('ROLE_USER', $roles)){$roleschecked[1]=1;}
	        	if (in_array('ROLE_AUTHOR', $roles)){$roleschecked[2]=1;}
	        	if (in_array('ROLE_ADMIN', $roles)){$roleschecked[3]=1;}
	        }
	        return $this->render('KeioStudyBundle:User:new.html.twig', array(
	            	'form'   => $form->createView(),
	            	'roleschecked'=>$roleschecked,
	        	));
	    }else{
	    	return $this->render('KeioStudyBundle:Member:register.html.twig', array(
	            'form'   => $form->createView(),
        	));
	    }

    }

    /**
     * Displays a form to create a new User entity.
     *
     */
    public function newAction()
    {
        $entity = new User();
        $form   = $this->createForm(new UserType(), $entity);

        $roleschecked = array(1=>0, 2=>0, 3=>0);
        return $this->render('KeioStudyBundle:User:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
            'roleschecked'=>$roleschecked,
        ));
    }

    /**
     * Finds and displays a User entity.
     *
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('KeioStudyBundle:User')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find User entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return $this->render('KeioStudyBundle:User:show.html.twig', array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),        ));
    }

    /**
     * Displays a form to edit an existing User entity.
     *
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('KeioStudyBundle:User')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find User entity.');
        }

        $editForm = $this->createForm(new UserType(), $entity);

        $roles = $entity->getRoles();
        $roleschecked = array(1=>0, 2=>0, 3=>0);
        if (count($roles)!=0){
        	if (in_array('ROLE_USER', $roles)){$roleschecked[1]=1;}
        	if (in_array('ROLE_AUTHOR', $roles)){$roleschecked[2]=1;}
        	if (in_array('ROLE_ADMIN', $roles)){$roleschecked[3]=1;}
        }

        return $this->render('KeioStudyBundle:User:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'roleschecked'=>$roleschecked,
        ));
    }

    /**
     * Edits an existing User entity.
     *
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();
        $user = $em->getRepository('KeioStudyBundle:User')->find($id);

        if (!$user) {
            throw $this->createNotFoundException('Unable to find User entity.');
        }

        $request = $this->getRequest();
        $data_form = $request->request->get('keio_studybundle_usertype');
    	$username = trim($data_form['username']);
    	$password = $data_form['password'];
    	$repeatpwd  = $request->request->get('pwdR');
        $roles = $request->request->get('roles');
        $user->setRoles($roles);

        $editForm = $this->createForm(new UserType(), $user);
        $editForm->bind($request);

        if ($editForm->isValid()) {
        	//chech nếu form có lỗi
	        $check_form = $this->checkFieldErrorsOfUser(1, $username, $data_form['email'], $password, $repeatpwd, $roles);
	        if ($check_form['ok']==0){//có lỗi
	        	$editForm->addError(new FormError($check_form['msg']));
	        }else{
	        	// encode the password
		        $factory = $this->get('security.encoder_factory');
		        $encoder = $factory->getEncoder($user);
		        $encodedPassword = $encoder->encodePassword($password, $user->getSalt());
		        $user->setPassword($encodedPassword);
		        $em->persist($user);
		        $em->flush();
				return $this->redirect($this->generateUrl('admin_user'));
	        }
        }


        $roleschecked = array(1=>0, 2=>0, 3=>0);
        if (count($roles)!=0){
        	if (in_array('ROLE_USER', $roles)){$roleschecked[1]=1;}
        	if (in_array('ROLE_AUTHOR', $roles)){$roleschecked[2]=1;}
        	if (in_array('ROLE_ADMIN', $roles)){$roleschecked[3]=1;}
        }
        return $this->render('KeioStudyBundle:User:edit.html.twig', array(
            'entity'      => $user,
            'edit_form'   => $editForm->createView(),
            'roleschecked'=>$roleschecked,
        ));
    }
    /**
     * Deletes a User entity.
     *
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('KeioStudyBundle:User')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find User entity.');
            }

            //check if contraint
			$checkconstraint = $em->getRepository('KeioStudyBundle:User')->checkConstraintToDeleteUser($id);
			if ($checkconstraint==1){ //having constraint
				$this->get('session')->getFlashBag()->add('msg', 'Delete failed because of constraint');
			}else{
				$em->remove($entity);
            	$em->flush();
			}
        }

        return $this->redirect($this->generateUrl('admin_user'));
    }

    /**
     * Creates a form to delete a User entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }

}
